package com.lelouch.wetlandcommon.common;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局异常处理
 *
 * @author lcy
 * @create 2018-03-01 10:26
 */
@Slf4j
@Component
public class ExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
        //对异常接口打印日志
        StringBuilder messageOfExceptionInterface = new StringBuilder();
        messageOfExceptionInterface.append("请求接口出现异常：{").append(request.getRequestURI())
                .append("}，请求参数：{").append(JSON.toJSONString(request.getParameterMap())).append("}");
        log.error(messageOfExceptionInterface.toString(), e);

        //组装异常统一返回接口
        ServerResponse serverResponse = null;

        String message = new StringBuilder().append("接口 [").append(request.getRequestURI()).append("] 出现异常!详细信息：").append(e.getMessage()).toString();
        serverResponse = ServerResponse.createByError(message, null);

        responseResult(response, serverResponse);
        return new ModelAndView();
    }

    private void responseResult(HttpServletResponse response, ServerResponse serverResponse) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setStatus(200);
        try {
            response.getWriter().write(JSON.toJSONString(serverResponse));
        } catch (IOException ex) {
            log.error(ex.getMessage());
        }
    }
}
